<?php

namespace app\api\controller\pachong;


use app\common\model\pachong\PachongProxyIp;
use app\common\model\pachong\tianqiyubao\PachongTianqiyubaoArea;
use app\common\model\pachong\tianqiyubao\PachongTianqiyubaoInfo;
use app\common\model\Tool;
use function think\p;

class TianqiyubaoController
{

    public function index()
    {
        $PachongTianqiyubaoAreaObj = PachongTianqiyubaoArea::instance()->findOrEmpty(111111)->toArray();
        //RedisService::instance()->hset("a","aaaa",100);
//        echo "aaaa";die;
//        print_r("");die;
//        (new RedisService())->hset("a","aaaa",100);
        $eday = date("Y-m-d", time());
        $ProxyIp = PachongProxyIp::instance()->getProxyIp();

        // 获取所有的地区
        $areaObjs = PachongTianqiyubaoArea::instance()->select()->toArray();
        foreach ($areaObjs as $areaObj){
            // 获取这个地区已经刷新时间的最大天数
            $PachongTianqiyubaoInfoObj = PachongTianqiyubaoInfo::instance()->where(['area_id'=>$areaObj['id']])->order('day desc')->findOrEmpty()->toArray();
            // 判断一下需要循环多少天,默认从2018.1.1开始获取数据
            $sday = $PachongTianqiyubaoInfoObj['day'] ?? "2018-01-01";

            if($eday != $sday){
                $dayArr = Tool::getDayRangeArr($sday,$eday);
                foreach ($dayArr as $day){
                    if($day == $sday){
                        continue;
                    }
                    // 调用本地python接口获取数据
                    $areaObj['url'] = str_replace(".html","",$areaObj['url']);
                    $areaObj['url'] = str_replace("lishi/","",$areaObj['url']);
                    $url = "127.0.0.1:8000" . PachongTianqiyubaoInfo::$pythonUrl . "?proxy_ip=".$ProxyIp."&url=" . $areaObj['web_url'].$areaObj['url'] . "/" . date("Ymd",strtotime($day)) . ".html";
                    $result = $this->getCurl($url);
                    if(!empty($result)){
                        $result['area_id'] = $areaObj['id'];
                        $result['area_name'] = $areaObj['name'];
                        $result['day'] = $day;
                    }
                    PachongTianqiyubaoInfo::instance()->insert($result);
                }
            }
        }
        return "结束";
    }


    public function getCurl($url)
    {
        $result = Tool::getCurl($url);
        if($result == null){
            sleep(10);
            return $this->getCurl($url);
        }
        if($result['code'] == 200){
            return $result['data'];
        }elseif ($result['code'] == 500){
            PachongProxyIp::instance()->flushProxyIp();
            return $this->getCurl($url);
        }else{
            return array();
        }
    }
}
